package cn.net.wanji.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileReader;
import cn.net.wanji.annotation.DataSource;
import cn.net.wanji.config.ApplicationConfig;
import cn.net.wanji.config.CommonParamConfig;
import cn.net.wanji.domain.AjaxResult;
import cn.net.wanji.entity.JsonRoot;
import cn.net.wanji.entity.VehicleRsuInfo;
import cn.net.wanji.entity.deviceInfo.DeviceInfo;
import cn.net.wanji.entity.deviceStatus.DeviceStatus;
import cn.net.wanji.enums.DataSourceType;
import cn.net.wanji.service.BookProducerService;
import cn.net.wanji.service.DataCopyService;
import cn.net.wanji.service.DataReceiveService;
import cn.net.wanji.utils.DateUtils;
import cn.net.wanji.utils.LogUtils;
import cn.net.wanji.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.log4j.Log4j2;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Map;

/**
 * @author guodejun
 * @createTime 2022/10/28 10:18
 * @description
 */

@Log4j2
@RestController
@RequestMapping(value = "/receive")
public class DataReceiveController {
    @Value("${kafka.topic.my-topic}")
    String myTopic;
    BookProducerService producer;
    DataReceiveController(BookProducerService producer) {
        this.producer = producer;
    }
    @Resource
    private DataReceiveService dataReceiveService;
    @Resource
    ApplicationConfig applicationConfig;

    @GetMapping("/entering")
    public AjaxResult entering() {
        String basePath = "C:/Users/wanji/Desktop/jsonData/";

        String[] fileNames = FileUtil.file(basePath).list();
        Arrays.stream(fileNames).forEach(item -> {
            String jsonText = new FileReader(basePath + item).readString();
            JsonRoot jsonRoot = JSONObject.parseObject(jsonText, JsonRoot.class);
            jsonRoot.getVehiclePicInfos().forEach(info -> {
                info.setHeadImage(null);
                info.setTailImage(null);
                info.setSideImage(null);
                info.setLicenseImage(null);
            });

            dataReceive(jsonRoot);
        });

        return AjaxResult.success();
    }

    @Resource
    private DataCopyService dataCopyService;

    @PostMapping("/data")
    public AjaxResult dataReceive(@RequestBody JsonRoot jsonRoot) {
        try {
            System.out.println(jsonRoot);
            if (jsonRoot == null || jsonRoot.getRecordId() == null) {
                return AjaxResult.error("jsonRoot is null");
            }

            dataReceiveService.dataReceive(jsonRoot);
            String fileNginx = applicationConfig.getFileNginx(jsonRoot.getRecordId());
            VehicleRsuInfo vehicleRsuInfo = jsonRoot.getVehicleRsuInfo(fileNginx);
            String s = JSON.toJSONString(vehicleRsuInfo);
            LocalDateTime detectTimeAsLocalDateTime = DateUtils.getDetectTimeAsLocalDateTime(vehicleRsuInfo.getDetectTime());
            // 这里我们假设如果最新更新时间在过去2分钟内没有变化，那么更新就是停滞的
            LocalDateTime tenMinutesAgo = LocalDateTime.now().minusMinutes(2);
            if(!"A".equals(vehicleRsuInfo.getRecordType())&&tenMinutesAgo.isBefore(detectTimeAsLocalDateTime)){
                System.out.println("kafka"+jsonRoot);
                this.producer.sendMessage(myTopic, s);
            }

//            dataCopyService.dataReceive(jsonRoot);
            return AjaxResult.success();
        } catch (Exception e) {
            LogUtils.errorLog(e);
            return AjaxResult.error(e.getMessage());
        }
    }


    public static void main(String[] args) {
        LocalDateTime tenMinutesAgo = LocalDateTime.now().minusMinutes(2);
        System.out.println(true);
    }

    /**
     * 0:正拍
     * 1:尾拍
     * 2:侧拍
     * 3:车牌
     * 4:短视频
     * @param files
     * @param fileTypes
     * @param recordId
     * @return
     */
    @PostMapping("/uploadFile")
    public AjaxResult uploadFile(@RequestParam("files") MultipartFile[] files, Integer[] fileTypes, String recordId,String unlawfulMold,String detectTime) {
        try {
            if (files == null || files.length == 0) {
                return AjaxResult.error("files 为空");
            } else if (recordId == null || "".equals(recordId)) {
                return AjaxResult.error("recordId 不能为空");
            } else if (fileTypes == null || fileTypes.length == 0) {
                return AjaxResult.error("fileTypes 不能为空");
            } else if (files.length != fileTypes.length) {
                return AjaxResult.error("files 与 fileTypes 长度不相同");
            } else if (StringUtils.isEmpty(detectTime)) {
                return AjaxResult.error("recordId: "+recordId+"detectTime不能为空");
            }
            // 存储
            dataReceiveService.saveFile(files, fileTypes, recordId,unlawfulMold,detectTime);

            return AjaxResult.success();
        } catch (Exception e) {
            LogUtils.errorLog(e);
            return AjaxResult.error(e.getMessage());
        }
    }

    @PostMapping("/deviceInfoData")
    public AjaxResult deviceInfoData(@RequestBody DeviceInfo deviceInfo) {
        try {
            if (deviceInfo == null || deviceInfo.getGantryId() == null) {
                return AjaxResult.error("deviceInfo is null");
            }
            dataReceiveService.deviceInfoData(deviceInfo);

            dataCopyService.deviceInfoData(deviceInfo);

            return AjaxResult.success();
        } catch (Exception e) {
            LogUtils.errorLog(e);
            return AjaxResult.error();
        }
    }

    @PostMapping("/deviceStatusData")
    public AjaxResult deviceStatusData(@RequestBody DeviceStatus deviceStatus) {
        try {
            if (deviceStatus == null || deviceStatus.getGantryId() == null) {
                return AjaxResult.error("deviceStatus is null");
            }
            dataReceiveService.deviceStatusData(deviceStatus);
            dataCopyService.deviceStatusData(deviceStatus);

            return AjaxResult.success();
        } catch (Exception e) {
            LogUtils.errorLog(e);
            return AjaxResult.error();
        }
    }

}
